package com.hecj.common.lib.excel;

import java.io.OutputStream;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/**
 * @类功能说明：从jfinal model中导出数据
 * @类修改者：
 * @修改日期：
 * @修改说明：
 * @作者：He Chaojie
 * @创建时间：2017-6-5 下午1:04:40
 * @版本：V1.0
 */

public class ModelCreateExcel implements CreateExcel {
	

	private Logger log = Logger.getLogger(ModelCreateExcel.class);
	
	@Override
	public WritableWorkbook create(AbstractSheet abstractSheet , OutputStream os) {
		
		ModelSheet modelSheet = (ModelSheet)abstractSheet;
		WritableWorkbook writableWorkbook = null;
		
		try {
			//创建工作表格
			writableWorkbook = Workbook.createWorkbook(os);
           
            // 生成名为“第一页”的工作表，参数0表示这是第一页
            WritableSheet sheet = writableWorkbook.createSheet(modelSheet.getSheetName()==null?"":modelSheet.getSheetName().trim(), 0);
            
            //标题头
            List<Column> columns = modelSheet.getColumns();
            if(columns != null){
            	for( int i = 0; i < columns.size() ; i++){
            		//列----->行
            		Column column = columns.get(i);
            		String colName = column.getTitle();
            		Label label = new Label(i, 0, colName==null?"":colName.trim());
            		sheet.addCell(label);
            	}
            }
            
            //数据
            List<?> models = modelSheet.getDatas();
            if(models != null){
            	//多少行
            	for(int i = 0 ;i<models.size();i++){
            		Object model = models.get(i);
            		//多少列
            		for( int j =0 ; j< columns.size() ;j++){
            			Column column = columns.get(j);
            			String field = column.getField();
            			String value = getObjectField(model,field);
            			Label label = new Label(j,i+1, value);
            			sheet.addCell(label);
            		}
            	}
            }
        } catch (Exception e) {
        	e.printStackTrace();
        	log.error("----error---导出Excel文件出错------");
        }
		return writableWorkbook;
	}
	
	private String getObjectField(Object obj, String field) {
		JSONObject m = JSON.parseObject(JSON.toJSONString(obj));
		String str =  obj2Str(m.get(field));
		return str == null ?"":str.trim();
	}
	
	public String obj2Str(Object obj){
		if(obj == null){
			return "";
		}
		if(obj instanceof Integer){
			return String.valueOf(obj);
		} else if(obj instanceof Long){
			return String.valueOf(obj);
		}
		return String.valueOf(obj);
	}
}
